package com.zhenyi.liuxue.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxActivity;
import com.liuxue.common.model.LxCompany;
import com.liuxue.common.model.LxFeedback;
import com.liuxue.common.model.LxRange;
import com.liuxue.common.model.LxSchool;
import com.liuxue.common.model.LxUser;
import com.liuxue.common.model.LxUserActivity;
import com.utils.PathUtils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

public class ActivityController extends AdminController {
	
	public void list() {
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindActivity");
		Page<LxActivity> pages = LxActivity.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/activity/index.html");
	}
	
	public void info() {
		setReferer();
		Long activityId = getParaToLong("activityId");
		if (activityId != null) {
			LxActivity info = LxActivity.dao.findById(activityId);
			if (info == null) {
				renderFailure(404, "info not found");
				return;
			}
			info.setContent(info.getContent().replace("<br />", "\n"));
			
			if (info.getRangeType().equals(2)) {
				Kv kv = Kv.create();
				kv.set("activityId", activityId);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					DBMap map = new DBMap();
					map.put("province", range.getProvince());
					map.put("city", range.getCity());
					locationLimit.add(map);
				}
				info.put("locationLimit", locationLimit);
				
			} else if (info.getRangeType().equals(3)) {
				Kv kv = Kv.create();
				kv.set("activityId", activityId);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> companyLimit = new ArrayList<>();
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					if (range.getCompanyId() != null) {
						DBMap map = new DBMap();
						map.put("id", range.getCompanyId());
						map.put("name", range.get("companyName"));
						companyLimit.add(map);
					}
					if (range.getLocation() != null) {
						String[] locationList = range.getLocation().split(",");
						DBMap map = new DBMap();
						map.put("province", locationList[0]);
						map.put("city", locationList.length > 1 ? locationList[1] : "");
						locationLimit.add(map);
					}
				}
				info.put("companyLimit", companyLimit);
				info.put("locationLimit", locationLimit);
			}
			
			setInfoItem(JsonKit.toJson(info));
		}
		List<LxSchool> schools = LxSchool.dao.findAll();
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindCompanies");
		List<LxCompany> companies = LxCompany.dao.find(sqlPara2);
		
		setAttr("schools", JsonKit.toJson(schools));
		setAttr("companies", JsonKit.toJson(companies));
		render("/lx/admin/activity/info.html");
	}
	
	public void submit() {
		Long id = getParaToLong("id");
		String title = getPara("title");
		String cover = getPara("cover");
		String video = getPara("video");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String content = getPara("content");
		String location = getPara("location");
		String url = getPara("url");
		Integer type = getParaToInt("type");
		Long schoolId = getParaToLong("schoolId");
		Integer isOver = getParaToInt("isOver");
		String enrollFields = getPara("enrollFields");
//		String visibility = getPara("visibility");
		Integer rangeType = getParaToInt("rangeType");
		String companyLimit = getPara("companyLimit");
		String locationLimit = getPara("locationLimit");
		
		content = content.replace("\n", "<br />");
		
		LxActivity info = null;
		if (id == null) {
			info = new LxActivity();
			info.save();
		} else {
			info = LxActivity.dao.findById(id);
			if (info == null) {
				renderFailure(404, "activity not found");
				return;
			}
		}
		info.setTitle(title);
		info.setCover(cover);
		info.setVideo(video);
		info.setStartTime(DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss"));
		info.setEndTime(DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss"));
		info.setContent(content);
		info.setLocation(location);
		info.setUrl(url);
		info.setType(type);
		info.setSchoolId(schoolId);
		info.setIsOver(isOver);
		info.setEnrollFields(enrollFields);
//		info.setVisibility(visibility);
		info.setRangeType(rangeType);
		boolean flag = info.update();
		if (flag) {
			// 处理可见范围
			Kv kv = Kv.create();
			if (id != null) {
				kv.set("activityId", info.getId());
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				for (LxRange range : rangeList) {
					range.delete();
				}
			}
			if ((rangeType.equals(2) || rangeType.equals(3)) && StrKit.notBlank(locationLimit)) {
				String[] locations = locationLimit.split(";");
				for (String loc : locations) {
					kv.set("activityId", info.getId());
					kv.set("location", loc);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setActivityId(info.getId());
						range.setLocation(loc);
						String[] provinceCity = loc.split(",");
						range.setProvince(provinceCity[0]);
						if (provinceCity.length > 1) {
							range.setCity(provinceCity[1]);
						} else {
							range.setCity("");
						}
						range.save();
					}
				}
			}
			if (rangeType.equals(3) && StrKit.notBlank(companyLimit)) {
				String[] idStrs = companyLimit.split(";");
				for (String idStr : idStrs) {
					kv.set("activityId", info.getId());
					kv.set("companyId", idStr);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setActivityId(info.getId());
						range.setCompanyId(Long.valueOf(idStr));
						range.save();
					}
				}
			}
		}
		renderFlag(flag);
	}
	
	public void delete() {
		Long activityId = getParaToLong("activityId");
		if (activityId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxActivity info = LxActivity.dao.findById(activityId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		renderFlag(info.delete());
	}
	
	public void enrollList() {
		Long activityId = getParaToLong("activityId");
		String province = getPara("province");
		String city = getPara("city");
		Long companyId = getParaToLong("companyId");
		Boolean attend = getParaToBoolean("attend");
		if (activityId == null) {
			renderFailure(500, "activity id is null");
			return;
		}
		LxActivity activity = LxActivity.dao.findById(activityId);
		if (activity == null) {
			renderFailure(404, "activity not found");
			return;
		}
		
		Kv kv = Kv.create();
		kv.set("activityId", activityId);
		if (StrKit.notBlank(province)) {
			kv.set("province", province);
			setAttr("province", province);
		}
		if (StrKit.notBlank(city)) {
			kv.set("city", city);
			setAttr("city", city);
		}
		if (companyId != null) {
			kv.set("companyId", companyId);
			setAttr("companyId", companyId);
		}
		if (attend != null && attend) {
			kv.set("attend", 1);
			setAttr("attend", 1);
		}
		if (getParaToInt("dl", 0).equals(1)) {
			downloadEnrollList(kv);
			return;
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindUserActivity", kv);
		Page<LxUserActivity> pages = LxUserActivity.dao.paginate(getPage(), getPageSize(), sqlPara);
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindCompanies");
		List<LxCompany> companies = LxCompany.dao.find(sqlPara2);

		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		setAttr("activity", JsonKit.toJson(activity));
		setAttr("companies", JsonKit.toJson(companies));
		render("/lx/admin/activity/enrollList.html");
	}
	
	public void enrollInfo() {
		Long activityId = getParaToLong("activityId");
		Long userId = getParaToLong("userId");
		if (userId == null || activityId == null) {
			renderFailure(500, "userId or activityId is null");
			return;
		}
		LxUserActivity info = LxUserActivity.dao.findById(activityId, userId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		if (info.getCompanyId() != null) {
			LxCompany company = LxCompany.dao.findById(info.getCompanyId());
			if (company != null) {
				info.put("companyName", company.getName());
			}
		}
		setInfoItem(JsonKit.toJson(info));
		render("/lx/admin/activity/enrollInfo.html");
	}
	
	public void deleteEnroll() {
		Long activityId = getParaToLong("activityId");
		Long userId = getParaToLong("userId");
		if (userId == null || activityId == null) {
			renderFailure(500, "userId or activityId is null");
			return;
		}
		LxUserActivity info = LxUserActivity.dao.findById(activityId, userId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		renderFlag(info.delete());
	}
	
	public void feedbackList() {
		Long activityId = getParaToLong("activityId");
		if (activityId == null) {
			renderFailure(500, "activity id is null");
			return;
		}
		LxActivity activity = LxActivity.dao.findById(activityId);
		if (activity == null) {
			renderFailure(404, "activity not found");
			return;
		}
		setAttr("activity", JsonKit.toJson(activity));
		
		Kv kv = Kv.create();
		kv.set("activityId", activityId);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindFeedback", kv);
		Page<LxFeedback> pages = LxFeedback.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/activity/feedbackList.html");
	}
	
	public void feedbackInfo() {
		Long feedbackId = getParaToLong("feedbackId");
		if (feedbackId == null) {
			renderFailure(500, "feedbackId is null");
			return;
		}
		LxFeedback info = LxFeedback.dao.findById(feedbackId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		if (info.getUserId() != null) {
			LxUser user = LxUser.dao.findById(info.getUserId());
			if (user != null) {
				info.put("userName", user.getName());
			}
		}
		setInfoItem(JsonKit.toJson(info));
		render("/lx/admin/activity/feedbackInfo.html");
	}
	
	public void deleteFeedback() {
		Long feedbackId = getParaToLong("feedbackId");
		if (feedbackId == null) {
			renderFailure(500, "feedbackId is null");
			return;
		}
		LxFeedback info = LxFeedback.dao.findById(feedbackId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		renderFlag(info.delete());
	}
	
	private void downloadEnrollList(Kv kv) {
		SqlPara sqlPara;
		sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindUserActivity", kv);
		List<LxUserActivity> items = LxUserActivity.dao.find(sqlPara);
		LxActivity activity = LxActivity.dao.findById(kv.get("activityId"));
		
		ArrayList<List<String>> arrayList = new ArrayList<>();
		List<String> title = CollUtil.newArrayList("姓名", "手机号", "邮箱", "生日", "省份", "城市", "公司", "职务",
				"如何了解到本次活动", "上申请季学生递交数", "上申请季学生入读数", "问题", "是否参与活动");
		arrayList.add(title);
		for (LxUserActivity info : items) {
			String name = info.getName();
			String mobile = info.getMobile();
			String email = info.getEmail();
			String birth = info.getBirth();
			String province = info.getProvince();
			String city = info.getCity();
			String companyName = info.get("companyName");
			String job = info.getJob();
			String channel = info.getChannel();
			String prevSubmit = info.getPrevSubmit().toString();
			String prevAdopt = info.getPrevAdopt().toString();
			String question = info.getQuestion();
			String attend = (info.getAttend() != null && info.getAttend() == 1) ? "是" : "否";

			List<String> row = CollUtil.newArrayList(name, mobile, email, birth, province, city, companyName, job,
					channel, prevSubmit, prevAdopt, question, attend);
			arrayList.add(row);
		}
		String now = DateUtil.now();
		now = now.replace("-", "");
		now = now.replace(":", "");
		now = now.replace(" ", "");
		String name = "报名名单-" + activity.getTitle() + "-" + now + ".xlsx";
		String path = PathUtils.getFile("lx", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.write(arrayList);
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

}
